package com.hack.validator;


import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 验证引擎类
 * 包含验证规则缓存和验证方法
 *
 * @author hack
 * @version 1.0
 * @date 2025/07/11
 */
@Component
public class ValidationEngine {
    private static final Map<String, List<ValidationRule>> RULE_CACHE = new ConcurrentHashMap<>();
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @Autowired
    private RuleService ruleService;
    private final String appId;
    @Autowired
    public ValidationEngine(@Value("${param.validator.app-id}")  String appId) {
        this.appId = appId;
        refreshRules();
        startRefreshScheduler();
    }

    public ValidationResult validate(Object param) {
        List<ValidationRule> rules = getRulesForApp();
        ValidationResult result = new ValidationResult();

        for (ValidationRule rule : rules) {
            try {
                Object value = getFieldValue(param, rule.getParamPath());
                if (!isValid(value, rule)) {
                    result.addError(rule.getParamPath(), rule.getErrorMsg());
                }
            } catch (Exception e) {
                result.addError(rule.getParamPath(), "Validation failed: " + e.getMessage());
            }
        }
        return result;
    }

    private List<ValidationRule> getRulesForApp() {
        return RULE_CACHE.computeIfAbsent(appId, id -> {
            try {
                return ruleService.getRules(id);
            } catch (SQLException e) {
                throw new RuntimeException("Failed to load validation rules", e);
            }
        });
    }

    private Object getFieldValue(Object obj, String fieldPath) throws Exception {
        String[] parts = fieldPath.split("\\.");
        Object current = obj;

        for (String part : parts) {
            if (current == null) {
                return null;
            }

            Field field;
            try {
                field = current.getClass().getDeclaredField(part);
            } catch (NoSuchFieldException e) {
                // Try with getter method
                String methodName = "get" + part.substring(0, 1).toUpperCase() + part.substring(1);
                try {
                    return current.getClass().getMethod(methodName).invoke(current);
                } catch (Exception ex) {
                    throw new NoSuchFieldException("Field or getter not found: " + part);
                }
            }

            field.setAccessible(true);
            current = field.get(current);
        }
        return current;
    }

    private boolean isValid(Object value, ValidationRule rule) {
        if (value == null) {
            return "NULL".equals(rule.getRuleType());
        }

        switch (rule.getRuleType()) {
            case "NOT_NULL":
                return value != null;
            case "NOT_EMPTY":
                return value != null && !value.toString().trim().isEmpty();
            case "MIN_LENGTH":
                int minLen = Integer.parseInt(rule.getRuleConfig());
                return value.toString().length() >= minLen;
            case "MAX_LENGTH":
                int maxLen = Integer.parseInt(rule.getRuleConfig());
                return value.toString().length() <= maxLen;
            case "RANGE":
                JSONObject config = new JSONObject(rule.getRuleConfig());
                double num = Double.parseDouble(value.toString());
                return num >= config.getDouble("min") && num <= config.getDouble("max");
            case "REGEX":
                return value.toString().matches(rule.getRuleConfig());
            case "EMAIL":
                return value.toString().matches("^[\\w-.]+@([\\w-]+\\.)+[\\w-]{2,4}$");
            default:
                return true; // Unknown rule type, pass by default
        }
    }

    private void refreshRules() {
        RULE_CACHE.remove(appId);
        getRulesForApp(); // Reload
    }

    private void startRefreshScheduler() {
        scheduler.scheduleAtFixedRate(this::refreshRules, 5, 5, TimeUnit.MINUTES);
    }

    public void clearCache() {
        RULE_CACHE.remove(appId);
    }
}